﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Microsoft.Win32;
using Zero.UControl.Base.Helper;
using static System.Net.WebRequestMethods;
using Point = System.Windows.Point;

namespace Zero.UControl.Component.ScreenCut
{
    /// <summary>
    /// ScreenShotWindow.xaml 的交互逻辑
    /// </summary>
    public partial class ScreenShotWindow : Window,INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler? PropertyChanged;
        private BitmapSource _screenshot;

        public ScreenShotWindow(BitmapSource screenshot)
        {
            InitializeComponent();
            _screenshot = screenshot;
            Activated += ScreenShotWindow_Activated;
            Deactivated += ScreenShotWindow_Deactivated;
            // 取得当前窗口所在显示器的 DPI
            // DPI 设备像素接口,表示的是每英寸像素点数
            // DIP 设备无关像素,存放的是相对值
            // WPF 的坐标系统是以 DPI=96 为基准的，1 DIP = 1 像素（仅当 DPI = 96 时）
            // 当系统的 DPI=144时，144/96=1.5，此时 1 DIP = 1.5 像素
            var dpi = VisualTreeHelper.GetDpi(this);

            // 加载截图 BitmapSource 到 Image 控件
            CapturedImage.Width = screenshot.PixelWidth / dpi.DpiScaleX;
            CapturedImage.Height = screenshot.PixelHeight / dpi.DpiScaleY;
            CapturedImage.Source = screenshot; // screenshot 为你的截图结果
        }

        private double scale = 1.0;

        public double Scale
        {
            get { return scale; }
            set 
            {
                scale = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Scale)));
            }
        }

        private void ScreenShotWindow_Activated(object? sender, EventArgs e)
        {
            WindowShadow.Color = Colors.DodgerBlue;
        }

        private void ScreenShotWindow_Deactivated(object? sender, EventArgs e)
        {
            WindowShadow.Color = Colors.Silver;
        }

        private void CopyImg_MenuItem_Click(object sender, RoutedEventArgs e)
        {
            Clipboard.SetImage(_screenshot);
        }

        private void Close_MenuItem_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }

        private async void Window_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            // 1. 检查鼠标是否在窗口内
            Point position = e.GetPosition(this);
            if (position.X < 0 || position.Y < 0 || position.X > this.ActualWidth || position.Y > this.ActualHeight)
                return;

            // 2. 更新缩放比例
            double delta = e.Delta > 0 ? 0.1 : -0.1;
            double newScale = Scale + delta;

            if (newScale < 0.3 || newScale > 3.0)
                return;
            Scale = newScale;

            // 3. 设置内容缩放
            ContentScaleTransform.ScaleX = Scale;
            ContentScaleTransform.ScaleY = Scale;

            // 4. 计算内容的新尺寸
            double contentWidth = CapturedImage.Source.Width * Scale;
            double contentHeight = CapturedImage.Source.Height * Scale;

            // 5. 设置窗口尺寸（含阴影边距）
            double margin = 20; // 阴影边距
            double newWindowWidth = contentWidth + margin;
            double newWindowHeight = contentHeight + margin;

            // 6. 应用位置和尺寸
            this.Width = newWindowWidth;
            this.Height = newWindowHeight;

            scaleBd.Visibility = Visibility.Visible;
            await Task.Delay(1500).ContinueWith(state =>
            {
                this.Dispatcher.Invoke(() =>
                {
                    scaleBd.Visibility = Visibility.Collapsed;
                });
            });
        }


        private void Rect_Button_Click(object sender, RoutedEventArgs e)
        {

        }

        private void Circle_Button_Click(object sender, RoutedEventArgs e)
        {

        }

        private void Arrow_Button_Click(object sender, RoutedEventArgs e)
        {

        }

        private void Pen_Button_Click(object sender, RoutedEventArgs e)
        {

        }

        private void Text_Button_Click(object sender, RoutedEventArgs e)
        {

        }

        private async void OCR_Button_Click(object sender, RoutedEventArgs e)
        {
            loading.Visibility = Visibility.Visible;
            //await Task.Run(() =>
            //{
            //    PaddleOCRSharp.OCRResult result = OCRHelper.Recognize(_screenshot);
            //    this.Dispatcher.Invoke(() =>
            //    {
            //        ocrText.Text = string.Join(" ", result.TextBlocks.Select(t => t.Text));
            //    });
            //});
            loading.Visibility = Visibility.Collapsed;
        }

        string initialDir = string.Empty;
        private void Save_Button_Click(object sender, RoutedEventArgs e)
        {
            // _screenshot
            SaveFileDialog dialog = new SaveFileDialog();
            dialog.Title = "请选择保存文件路径";
            if (!string.IsNullOrEmpty(initialDir))
            {
                dialog.InitialDirectory = initialDir;
            }

            bool? flag = dialog.ShowDialog();
            if(flag.HasValue && flag.Value == true)
            {
                string filePath = dialog.FileName;
                initialDir = Directory.GetParent(filePath).FullName;
                ImageHelper.BitmapSourceToImage(_screenshot).Save(filePath);
            }
        }
    }
}
